package memorphic.utils
{
	public class StringTypes
	{

		public static const STRING:String = "String";
		public static const NUMBER:String = "Number";
		public static const INT:String = "int";
		public static const UINT:String = "uint";
		public static const BOOLEAN:String = "Boolean";
		public static const ARRAY:String = "Array";
		public static const DATE:String = "Date";


		public static function stringToNumber(strValue:String):Number
		{
			var value:Number = parseFloat(strValue);
			if(isNaN(value)){
				throw new Error("Value '" + value + "' cannot be converted to a Number");
			}else{
				return value;
			}
		}


		public static function stringToInt(strValue:String, truncate:Boolean=true):int
		{
			var numValue:Number = stringToNumber(strValue);
			if(numValue % 1 == 0){
				return numValue as int;
			}else if(truncate){
				return Math.floor(numValue);
			}else{
				throw new Error("Value '" + strValue + "' cannot be converted to a int");
			}
		}

		public static function stringToUint(strValue:String, truncate:Boolean=true, abs:Boolean=true):uint
		{
			var intValue:int = stringToInt(strValue, truncate);
			if(intValue < 0){
				if(abs){
					return Math.abs(intValue) as uint;
				}else{
					throw new Error("Value '" + strValue + "' cannot be converted to a uint");
				}
			}else {
				return intValue as uint;
			}
		}


		public static function stringToBoolean(strValue:String, caseSensitive:Boolean=true):Boolean
		{
			var value:String = strValue;	//getConfigParamString(strValueid);
			if(!caseSensitive){
				value = value.toLowerCase();
			}
			if(value == "true"){
				return true;
			}else if(value == "false"){
				return false;
			}else{
				throw new Error("Value '" + value + "' cannot be converted to a Boolean");
			}

		}



		public static function stringToDate(strValue:String):Date
		{
			return new Date(strValue);
		}


		/**
		 * XXX: For some reason, Flex doesn't like a Regexp as a default parameter
		 */
		public static function stringToArray(strValue:String, separator:*=",", contentType:String=STRING):Array
		{
			var values:Array = strValue.split(separator);
			if(contentType != STRING){
				var n:int = values.length;
				for(var i:int=0; i<n; i++){
					values[i] = stringToType(values[i] as String, contentType);
				}
			}
			return values;
		}


		public static function stringToType(strValue:String, contentType:String=STRING):Object
		{
			switch(contentType){
			case STRING:
				return strValue;
			case BOOLEAN:
				return stringToBoolean(strValue);
			case INT:
				return stringToInt(strValue);
			case UINT:
				return stringToUint(strValue);
			case NUMBER:
				return stringToNumber(strValue);
			case ARRAY:
				return stringToArray(strValue);
			case DATE:
				return stringToDate(strValue);
			}
			return null;
		}

	}
}